<?php

class MallAction extends Action {
	
	public function updateLMallSetting($cid, $appId, $appSecret, $paySignKey,$partnerId,$partnerKey) {
	
		$CustomerMallSettingModel = D('customer_mall_setting');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$data['appId'] = trim($appId);
		$data['appSecret'] = trim($appSecret);
		$data['paySignKey'] = trim($paySignKey);
		$data['partnerId'] = trim($partnerId);
		$data['partnerKey'] = trim(partnerKey);
		$data['updateTime'] = date('Y-m-d H:i:s');
	
		$condition['customerId'] = array('eq',$cid);
		$logistics = $CustomerMallSettingModel->where($condition)->find();
	
		if($logistics){
			$result = $CustomerMallSettingModel->where($condition)->save($data);
				
			if($result !== false){
				Output::instance()->resultCode(code_success,"配置成功");
			}else{
				Output::instance()->resultCode(code_sql_error,'数据保存失败');
			}
				
		}else{
			$data['customerId'] = $cid;
				
			$result = $CustomerMallSettingModel->add($data);
				
			if($result){
				Output::instance()->resultCode(code_success,"配置成功");
			}else{
				Output::instance()->resultCode(code_sql_error,'数据保存失败');
			}
		}
	}
	
	
	public function getMallSetting($cid) {
		$CustomerMallSettingModel = D('customer_mall_setting');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$condition['customerId'] = array('eq',$cid);
		$result = $CustomerMallSettingModel->where($condition)->find();
	
		if (!isset($result)) {
			Output::instance()->resultCode(code_sql_error);
			return;
		}
	
		Output::instance()->object($result);
	}
	
	/*
	 * 获取配送设置
	 */
	public function getDeliverySetting($id=null) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$CustomerSuperSettingModel = D('customer_super_setting');
        $distriDepotModel = M('module_distribution_depot');
		$condition['customerId'] = array('eq',$customerId);
		$setting = $CustomerSuperSettingModel->where($condition)
		->field("allowPickUp, allowDelivery")->find();
		Session::switchCustomer($customerId);
		$distriScheme = M("module_distribution_scheme");
		if (!$setting) {
			Output::instance()->resultCode(code_product_logistics_invalid);
			return;
		}
		$DeliveryTypeModel = M('module_mall_delivery_type');
		$deliveryWhere['a.distributionId']=array('eq',$id);
		$deliveryType = $DeliveryTypeModel->alias("a")
			->join("wx_store_district_category b on find_in_set(b.id,a.categoryIds)")
			->where($deliveryWhere)
			->field("a.deliveryTypeText,a.deliveryTypeValue,a.isDefault,a.categoryIds,group_concat(b.name) as name")
			->group("a.id")
			->select();

        // 如果是物流配送, 选上仓库
        for($i = 0; $i < count($deliveryType); $i++) {
            if ($deliveryType[$i]['deliveryTypeValue'] == 'delivery') {
                $distriDepotWhere['distributionId'] = array('eq', $id);
                $deliverParam = $distriDepotModel->alias('distriDepot')
                    ->where($distriDepotWhere)
                    ->join('wx_depot depot on distriDepot.depotId = depot.id')
                    ->field('depot.id, name')
                    ->select();
                $deliveryType[$i]['categoryIds'] = $deliverParam[0]['id'];
                $deliveryType[$i]['name'] = $deliverParam[0]['name'];
            }
        }

		$deliveryArr = array();
		if($setting["allowPickUp"] == 1) {
			$isFind = false;
			foreach ($deliveryType as $temp) {
				if ($temp["deliveryTypeValue"] == ORDER_DELIVERYTYPE_PICKUP) {
					$temp["isChecked"] = 1;
					array_push($deliveryArr, $temp);
					$isFind = true;
					break;
				}
			}
			if (!$isFind) {
				$tempNone["deliveryTypeText"] = ORDER_DELIVERYTYPE_PICKUP_TEXT;
				$tempNone["deliveryTypeValue"] = ORDER_DELIVERYTYPE_PICKUP;
				$tempNone["isDefault"] = 0;
				$tempNone["isChecked"] = 0;
				array_push($deliveryArr, $tempNone);
			}
		}
		if($setting["allowDelivery"] == 1) {
			$isFind = false;
			foreach ($deliveryType as $temp) {
				if ($temp["deliveryTypeValue"] == ORDER_DELIVERYTYPE_DELIVERY) {
					$temp["isChecked"] = 1;
					array_push($deliveryArr, $temp);
					$isFind = true;
					break;
				}
			}
			if (!$isFind) {
				$tempNone["deliveryTypeText"] = ORDER_DELIVERYTYPE_DELIVERY_TEXT;
				$tempNone["deliveryTypeValue"] = ORDER_DELIVERYTYPE_DELIVERY;
				$tempNone["isDefault"] = 0;
				$tempNone["isChecked"] = 0;
				array_push($deliveryArr, $tempNone);
			}
		}
		
		$result["deliveryType"] = $deliveryArr;
	
		$CostModel = M('module_mall_delivery_cost');
		$costWhere['distributionId']=array('eq',$id);
		$deliveryCost = $CostModel->where($costWhere)->select();
		$distriWhere['id']=array('eq',$id);
		$distriInfo = $distriScheme->where($distriWhere)->field('name,mallUrl')->find();
		$result['distriName']=$distriInfo['name'];
		$result['mallUrl']=$distriInfo['mallUrl'];
		if ($deliveryCost === false) {
			Output::instance()->resultCode(code_sql_error);
			Log::write($CostModel->getLastSql());
			return;
		}
		$result["deliveryCost"] = $deliveryCost;
		Output::instance()->object($result);
	}
	//设置门店自提 门店分类
	public function getCategoryNames($categoryIds){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$category = M("store_district_category");
		Session::switchCustomer($customerId);
		$result = $category->where("id in ($categoryIds)")->field("group_concat(name) as names")->find();
		if($result){
			Output::instance()->object($result);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}

	}

    /**
     * 用户店铺提供的配送方式设置
     *
     * @param        $name                  配送方式名称
     * @param        $mallUrl               门店URL
     * @param        $costName              物流名称(申通快递)
     * @param        $cost                  物流费用设置
     * @param int    $supportPickup         是否支持门店自取
     * @param int    $supportDelivery       是否支持物流配送
     * @param string $default               是否设置了默认
     * @param null   $distriId              方式序号id
     * @param null   $pickupCategoryIds     门店自取的门店类别id
     *
     * @modify lilei<LL_strive@163.com> 2017-03-29
     */
	public function setDeliverySetting(
	    $name,
        $mallUrl,
        $costName,
        $cost,
        $depot,
        $supportPickup = 0,
        $supportDelivery = 0,
        $default = '',
        $distriId = null,
        $pickupCategoryIds = null
    ) {
	    /** 1. 先拿到当前用户的id */
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 2. 实例化数据模型 */
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$CustomerSuperSettingModel = D('customer_super_setting');
		$condition['customerId'] = array('eq',$customerId);
		$setting = $CustomerSuperSettingModel
            ->where($condition)
			->field("allowPickUp, allowDelivery")
            ->find();

        $distriDepot  = M('module_distribution_depot');
		Session::switchCustomer($customerId);
		$distriScheme = M('module_distribution_scheme');

        /** 3. 对数据库中查询得到的数据进行校验 */
		if (!$setting) {
			Output::instance()->resultCode(code_product_logistics_invalid);
			return;
		}
		
		if ((empty($setting["allowPickUp"]) && $supportPickup)
				|| (empty($setting["allowDelivery"]) && $supportDelivery)) {
			Output::instance()->resultCode(code_product_logistics_no_right);
			return;
		}

		/** 4. 组合数据 */
		$distriData['name']     = $name;
		$distriData['mallUrl']  = $mallUrl;

		if($distriId) { // 修改
			$distriData['updateTime'] = date("Y-m-d H:i:s");
			$distriWhere['id'] = array('eq', $distriId);
			$distriScheme->where($distriWhere)->save($distriData);

            // 如果修改配送方式, 则暂时先删除该配送下所有的仓库
            $distriDepotWhere['distributionId'] = array('eq', $distriId);
            $distriDepotWhere['cid']            = array('eq', $customerId);
            $distriDepot->where($distriDepotWhere)->delete();
		} else {        // 新建
			$distriData['createTime'] = date("Y-m-d H:i:s");
			$distriData['updateTime'] = date("Y-m-d H:i:s");
			$distriId = $distriScheme->add($distriData);
		}

		// 无论是修改还是新增, 都添加配送方式与仓库的关联, 前提是选择了物流配送
        if ($supportDelivery && $depot) { // 支持物流配送, 并且选择了仓库
            $depotData = [
                'cid'            => $customerId,
                'distributionId' => $distriId,
                'depotId'        => $depot,
                'createTime'     => date("Y-m-d H:i:s")
            ];
            $distriDepotId = $distriDepot->add($depotData);
        }

		/** 5. 存储该方式下配送类型数据 */
		$result = $this->setDeliveryType($distriId, $supportPickup, $supportDelivery, $default, $pickupCategoryIds);
		if ($result === false) {
			return;
		}

		/** 6. 设置物流费用 */
		$cost = json_decode($cost);
		$result = $this->setDeliveryCost($distriId,$costName, $cost);
		if ($result !== false) {
		    $Out['code'] = 0;
            $Out['msg'] = 'ok';
            $Out['id'] = $distriId;
			Output::instance()->object($Out);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

    /**
     * 设置配送方式中的配送类型的内容
     *
     * @param      $distributionId
     * @param      $supportPickup       支持自取
     * @param      $supportDelivery     支持物流
     * @param      $default             默认
     * @param null $pickupCategoryIds   自取门店类别
     * @return bool                     设置是否成功
     *
     * @modify lilei<LL_strive@163.com> 2017-03-29
     */
	private function setDeliveryType($distributionId, $supportPickup, $supportDelivery, $default, $pickupCategoryIds = null)
    {
        /** 1. 实例化模型 */
		$DeliveryTypeModel = M('module_mall_delivery_type');

        /** 2. 组织数据 */
		$dataArr = array();
		if ($supportPickup) {   // 支持门店自取的数据
			$data = array();
			$data['distributionId']     = $distributionId;
			$data["deliveryTypeText"]   = ORDER_DELIVERYTYPE_PICKUP_TEXT;
			$data["deliveryTypeValue"]  = ORDER_DELIVERYTYPE_PICKUP;
            $data["isDefault"]          = ($default == ORDER_DELIVERYTYPE_PICKUP) ? 1 : 0;
			$data['categoryIds']        = $pickupCategoryIds;
			array_push($dataArr, $data);
		}
		if ($supportDelivery) { // 支持物流的数据
			$data = array();
			$data['distributionId']     = $distributionId;
			$data["deliveryTypeText"]   = ORDER_DELIVERYTYPE_DELIVERY_TEXT;
			$data["deliveryTypeValue"]  = ORDER_DELIVERYTYPE_DELIVERY;
            $data["isDefault"]          = ($default == ORDER_DELIVERYTYPE_DELIVERY) ? 1 : 0;
            $data['categoryIds']        = '';
			array_push($dataArr, $data);
		}

		/** 3. 存储数据 */
		if (count($dataArr) > 0) {
		    // 先删除旧的存储内容
			$where['distributionId'] = array('eq', $distributionId);
			$DeliveryTypeModel->where($where)->delete();
            // 再将新内容存储
			$result = $DeliveryTypeModel->addAll($dataArr);
            // 最后检测一下存储结果
			if (!$result) {
				Output::instance()->resultCode(code_sql_error);
				return false;
			}
		}
		return true;
	}

    /**
     * 设置配送方式的物流费用
     *
     * @param $distributionId   方式序号id
     * @param $costName         物流名称
     * @param $costArr          物流价格阶梯数组
     * @return bool|string
     *
     * @modify lilei<LL_strive@163.com> 2017-03-29
     */
	private function setDeliveryCost($distributionId, $costName, $costArr)
    {
        /** 1. 实例化数据模型 */
		$CostModel = M('module_mall_delivery_cost');

        /** 2. 组织数据 */
		$dataArr = array();
		foreach ($costArr as $costObj) {
			$data = array();
			$data['distributionId'] = $distributionId;
			$data["costName"]       = $costName;
			$data["maxPrice"]       = $costObj->maxPrice;
			$data["cost"]           = $costObj->cost;
			$data["points"]         = $costObj->points;
			array_push($dataArr, $data);
		}

		/** 3. 数据存储并返回 */
		if (count($dataArr) > 0) {
			$where['distributionId']=array('eq',$distributionId);
			$CostModel->where($where)->delete();
			$result = $CostModel->addAll($dataArr);
			return $result;
		} else {
			return true;
		}
	}
	public function distributionSetDefault($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer($customerId);
		$distribution = M("module_distribution_scheme");
		$disWhere['isDefault']=array('eq',1);
		$disData['isDefault']=0;
		$disData['updateTime'] = date("Y-d-m H:i:s");
		$distribution->where($disWhere)->save($disData);
		$where['id']=array('eq',$id);
		$data['isDefault']=1;
		$data['updateTime']=date("Y-d-m H:i:s");
		$result = $distribution->where($where)->save($data);
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}

	}
	public function distributionDeleted($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer($customerId);
		$distribution = M("module_distribution_scheme");
		$where['id']=array('eq',$id);
		$data['deleted']=1;
		$data['updateTime']=date("Y-d-m H:i:s");
		$result = $distribution->where($where)->save($data);
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}

	}

	public function getPaySetting() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
	
		$CustomerSuperSettingModel = D('customer_super_setting');
		$condition['customerId'] = array('eq', $customerId);
		$setting = $CustomerSuperSettingModel->where($condition)
			->field("allowAiNongPay,allowWXPay, allowTransfer, allowUPay,allowTenPay, allowDeliveryPay, allowStored,allowAliPay")->find();
	
		Session::switchCustomer($customerId);
		if (!$setting) {
			Output::instance()->resultCode(code_product_paytype_invalid);
			return;
		}
	
		$PayTypeModel = M('module_mall_pay_type');
		$payType = $PayTypeModel->field("payTypeText, payTypeValue, isDefault")->select();
		if ($payType === false) {
			Output::instance()->resultCode(code_sql_error);
			Log::write($PayTypeModel->getLastSql());
			return;
		}
		
		$payTypeArr = array();
		if($setting["allowAiNongPay"] == 1) {
			$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_AINONGPAY_TEXT, ORDER_PAYTYPE_AINONGPAY);
			array_push($payTypeArr, $data);
		}
		if($setting["allowWXPay"] == 1) {
			$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_WXPAY_TEXT, ORDER_PAYTYPE_WXPAY);
			array_push($payTypeArr, $data);
		}
		if($setting["allowAliPay"] == 1) {
			$data = $this->addPayTypeToArr($payType, "支付宝", "alipay");
			array_push($payTypeArr, $data);
		}
		if($setting["allowTransfer"] == 1) {
			$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_TRANSFER_TEXT, ORDER_PAYTYPE_TRANSFER);
			array_push($payTypeArr, $data);
		}
		
		if ($setting["allowDeliveryPay"] == 1) {
			$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_DELIVERIY_PAY_TEXT, ORDER_PAYTYPE_DELIVERIY_PAY);
			array_push($payTypeArr, $data);
		}
		
		if ($setting["allowStored"] == 1) {
			$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_STORED_PAY_TEXT, ORDER_PAYTYPE_STORED_PAY);
			array_push($payTypeArr, $data);
		}
		
		if ($setting["allowUPay"] == 1) {
			$data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_UPAY_TEXT, ORDER_PAYTYPE_UPAY);
			array_push($payTypeArr, $data);
		}
		
		
		if ($setting["allowTenPay"] == 1) {
		    $data = $this->addPayTypeToArr($payType, ORDER_PAYTYPE_TENPAY_TEXT, ORDER_PAYTYPE_TENPAY);
		    array_push($payTypeArr, $data);
		}
		$result["payType"] = $payTypeArr;
		
// 		$result["wxpay"] = $this->getWxPay();
		Output::instance()->object($result);
	}
	
	private function addPayTypeToArr($searchArr, $payTypeText, $payTypeValue) {

		foreach ($searchArr as $temp) {
			if ($temp["payTypeValue"] == $payTypeValue) {
				$temp["isChecked"] = 1;
				return $temp;
			}
		}
		$tempNone["payTypeText"] = $payTypeText;
		$tempNone["payTypeValue"] = $payTypeValue;
		$tempNone["isDefault"] = 0;
		$tempNone["isChecked"] = 0;
		return $tempNone;
	}
	
	public function setPaySetting($supportWxpay = 0, $supportDelivery = 0, $supportStored = 0,
			$supportTransfer = 0, $supportUpay = 0,$supportAlipay = 0,$supportTenpay = 0, $default = '',$supportAinongpay) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerSuperSettingModel = D('customer_super_setting');
		$condition['customerId'] = array('eq', $customerId);
		$setting = $CustomerSuperSettingModel->where($condition)
			->field("allowWXPay, allowTransfer, allowUPay,allowTenPay, allowDeliveryPay, allowStored,allowAliPay,allowAliPay,allowAiNongPay")->find();
		
		Session::switchCustomer($customerId);
		if (!$setting) {
			Output::instance()->resultCode(code_product_paytype_invalid);
			return;
		}
		
		if ((empty($setting["allowWXPay"]) && $supportWxpay)
				|| (empty($setting["allowTransfer"]) && $supportTransfer)
				|| (empty($setting["allowUPay"]) && $supportUpay)
		        || (empty($setting["allowTenPay"]) && $supportTenpay)
				|| (empty($setting["allowDeliveryPay"]) && $supportDelivery) 
				|| (empty($setting["allowStored"]) && $supportStored)
				|| (empty($setting["allowAiNongPay"]) && $supportAinongpay)
				|| (empty($setting["allowAliPay"]) && $supportAlipay) ) {
			Output::instance()->resultCode(code_product_paytype_no_right);
			return;
		}
		
		$result = $this->setPayType($supportWxpay, $supportDelivery, $supportStored,
			 $supportTransfer, $supportUpay,$supportTenpay, $supportAlipay,$default,$supportAinongpay);
		if($result === false){
			return;
		}
        R('Log/add', array('payManage', '', '支付方式管理', op_update, '', '更新支付方式设置'));
		
		Output::instance()->resultCode();
	}
	
	public function setWxPayOldSetting($appId, $appSecret, $paySignKey, $partnerId, $partnerKey) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$customerId = Session::$user["customerId"];
		
		Session::switchCustomer(0);
		$CustomerMallSettingModel = D('customer_mall_setting');
		Session::switchCustomer($customerId);
		
		$data['appId'] = trim($appId);
		$data['appSecret'] = trim($appSecret);
		$data['paySignKey'] = trim($paySignKey);
		$data['partnerId'] = trim($partnerId);
		$data['partnerKey'] = trim($partnerKey);
		
		$data['mchId'] = NULL;
		$data['payKey'] = NULL;
		$data['isOld'] = 1;
		
		$data['updateTime'] = date('Y-m-d H:i:s');
		
		$condition['customerId'] = array('eq',$customerId);
		$mallSetting = $CustomerMallSettingModel->where($condition)->find();
		
		if($mallSetting){
			$result = $CustomerMallSettingModel->where($condition)->save($data);
		}else{
			$data['customerId'] = $customerId;
			$result = $CustomerMallSettingModel->add($data);
		}
		if ($result !== false) {
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	
	
	public function setWxPaySetting($appId, $mchId, $payKey,$merchantMode=0,$subMechId=null,$subAppId=null,$merchantMechId=null,$merchantKey=null) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	
		$customerId = Session::$user["customerId"];
	
		Session::switchCustomer(0);
		$CustomerMallSettingModel = D('customer_mall_setting');
		Session::switchCustomer($customerId);
	
		$data['appId'] = trim($appId);
		$data['mchId'] = trim($mchId);
		$data['payKey'] = trim($payKey);
		$data['merchantMode'] = trim($merchantMode);
		$data['subMechId'] = trim($subMechId);
		$data['subAppId'] = trim($subAppId);
		$data['merchantMechId'] = trim($merchantMechId);
		$data['merchantKey'] = trim($merchantKey);

		$data['paySignKey'] = NULL;
		$data['partnerId'] = NULL;
		$data['partnerKey'] = NULL;
		
		$data['isOld'] = 0;
		$data['updateTime'] = date('Y-m-d H:i:s');
	
		$condition['customerId'] = array('eq',$customerId);
		$mallSetting = $CustomerMallSettingModel->where($condition)->find();
	
		if($mallSetting){
			$result = $CustomerMallSettingModel->where($condition)->save($data);
		}else{
			$data['customerId'] = $customerId;
			$result = $CustomerMallSettingModel->add($data);
		}
		if ($result !== false) {
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	
	public function getWxPaySetting() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
	
		$CustomerMallSettingModel = D('customer_mall_setting');
		$condition['customerId'] = $customerId;
		$result = $CustomerMallSettingModel->where($condition)->find();
		if ($result) {
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode();
		}
	}
	//获得支付宝支付信息
	public function getAliPaySetting() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerMallSettingModel = D('customer_mall_alipay_setting');
		$condition['customerId'] = $customerId;
		$result = $CustomerMallSettingModel->where($condition)->find();
		// echo $CustomerMallSettingModel->getLastSql();
		if ($result) {
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode();
		}
	}
	//设置支付宝信息
	public function setAliPaySetting($appId, $rsaPrivateKey,$alipayrsaPublicKey,$alipayPublicKey) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$CustomerMallSettingModel = D('customer_mall_alipay_setting');
		Session::switchCustomer($customerId);
		$data['appId'] = trim($appId);
		$data['rsaPrivateKey'] = trim($rsaPrivateKey);
		$data['alipayrsaPublicKey'] = trim($alipayrsaPublicKey);
		$data['alipayPublicKey'] = trim($alipayPublicKey);
		$data['updateTime'] = date('Y-m-d H:i:s');

		$condition['customerId'] = array('eq',$customerId);
		$mallSetting = $CustomerMallSettingModel->where($condition)->find();
		if($mallSetting){
			$result = $CustomerMallSettingModel->where($condition)->save($data);
		}else{
			$data['createTime'] = date('Y-m-d H:i:s');
			$data['customerId'] = $customerId;
			$result = $CustomerMallSettingModel->add($data);
		}
		if ($result !== false) {
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//ihziluoh  添加财付通支付信息 开始
	public function getTenPaySetting() {
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	
	    $customerId = Session::$user["customerId"];
	    Session::switchCustomer(0);
	
	    $CustomerMallSettingModel = D('customer_mall_tenpay_setting');
	    $condition['customerId'] = $customerId;
	    $result = $CustomerMallSettingModel->where($condition)->find();
	   // echo $CustomerMallSettingModel->getLastSql();
	    if ($result) {
	        Output::instance()->object($result);
	    } else {
	        Output::instance()->resultCode();
	    }
	}

	public function setTenPaySetting($mchId, $payKey,$password) {
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	
	    $customerId = Session::$user["customerId"];
	
	    Session::switchCustomer(0);
	    $CustomerMallSettingModel = D('customer_mall_tenpay_setting');
	    Session::switchCustomer($customerId);
	
	  //  $data['appId'] = trim($appId);
	    $data['mchId'] = trim($mchId);
	    $data['payKey'] = trim($payKey);
	    $data['password'] = trim($password);
	   // $data['paySignKey'] = NULL;
	    //$data['partnerId'] = NULL;
	    //$data['partnerKey'] = NULL;
	
	   // $data['isOld'] = 0;
	    $data['updateTime'] = date('Y-m-d H:i:s');
	
	    $condition['customerId'] = array('eq',$customerId);
	    $mallSetting = $CustomerMallSettingModel->where($condition)->find();
	
	    if($mallSetting){
	        $result = $CustomerMallSettingModel->where($condition)->save($data);
	    }else{
	        $data['createTime'] = date('Y-m-d H:i:s');
	        $data['customerId'] = $customerId;
	        $result = $CustomerMallSettingModel->add($data);
	    }
	    if ($result !== false) {
	        Output::instance()->resultCode();
	    } else {
	        Output::instance()->resultCode(code_sql_error);
	    }
	}
	
	//ihziluoh   财付通支付信息 结束
	
	private function setPayType($supportWxpay, $supportDelivery, $supportStored,
			 $supportTransfer, $supportUpay,$supportTenpay, $supportAlipay,$default,$supportAinongpay) {
		$PayTypeModel = M('module_mall_pay_type');
	
		$dataArr = array();
		if ($supportAlipay) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_ALIPAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_ALIPAY;
			if ($default == ORDER_PAYTYPE_ALIPAY) {
				$data["isDefault"] = 1;
			} else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		if ($supportWxpay) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_WXPAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_WXPAY;
			if ($default == ORDER_PAYTYPE_WXPAY) {
				$data["isDefault"] = 1;
			} else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		if ($supportDelivery) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_DELIVERIY_PAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_DELIVERIY_PAY;
			if ($default == ORDER_PAYTYPE_DELIVERIY_PAY) {
				$data["isDefault"] = 1;
			}else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		if ($supportStored) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_STORED_PAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_STORED_PAY;
			if ($default == ORDER_PAYTYPE_STORED_PAY) {
				$data["isDefault"] = 1;
			}else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		if ($supportTransfer) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_TRANSFER_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_TRANSFER;
			if ($default == ORDER_PAYTYPE_TRANSFER) {
				$data["isDefault"] = 1;
			}else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		if ($supportUpay) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_UPAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_UPAY;
			if ($default == ORDER_PAYTYPE_UPAY) {
				$data["isDefault"] = 1;
			}else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		
		
		if ($supportTenpay) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_TENPAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_TENPAY;
			if ($default == ORDER_PAYTYPE_TENPAY) {
				$data["isDefault"] = 1;
			}else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}
		if ($supportAinongpay) {
			$data = array();
			$data["payTypeText"] = ORDER_PAYTYPE_AINONGPAY_TEXT;
			$data["payTypeValue"] = ORDER_PAYTYPE_AINONGPAY;
			if ($default == ORDER_PAYTYPE_AINONGPAY) {
				$data["isDefault"] = 1;
			}else {
				$data["isDefault"] = 0;
			}
			array_push($dataArr, $data);
		}

		if (count($dataArr) > 0) {
			$PayTypeModel->execute('truncate table __TABLE__');
			$result = $PayTypeModel->addAll($dataArr);
			if (!$result) {
				Log::write($PayTypeModel->getDbError());
				Output::instance()->resultCode(code_sql_error);
				return false;
			}
		}
		return true;
	}
	
	/*
	 * 获取支持的支付方式和配送方式
	 * price订单金额
	 * points订单积分
	 * selPayType 上次选择的支付方式
	 * selDeliveryType 上次选择的配送方式
	 */
	public function getPayAndLogisticsList($prices, $points, $selPayType, $selDeliveryType, $cids,$distributionId=NULL) {
		$DeliveryTypeModel = M('module_mall_delivery_type');
		$distriSchemeModel = M('module_distribution_scheme');
		if($distributionId){
			$deliveryType = $DeliveryTypeModel->where("distributionId=$distributionId")
				->field("deliveryTypeText as text, deliveryTypeValue as value,isDefault")
				->select();
		}else{
			$deliveryType = $distriSchemeModel->alias("a")
				->join("inner join wx_".$cids."_module_mall_delivery_type b on a.id=b.distributionId")
				->field("b.deliveryTypeText as text, b.deliveryTypeValue as value,b.isDefault")
				->where("a.isDefault = 1")
				->select();
		}
		if ($deliveryType === false) {
			Log::write('getPayAndLogisticsListData deliveryType:' . $DeliveryTypeModel->getLastSql());
			return;
		}
		
		$PayTypeModel = M('module_mall_pay_type');
		$payType = $PayTypeModel->field("payTypeText as text, payTypeValue as value, isDefault")->select();
		if ($payType === false) {
			Log::write('getPayAndLogisticsListData payType:' . $PayTypeModel->getLastSql());
			return;
		}
		
		// 将上次选择的配送方式设置为默认， 判断是否已经有默认值，没有默认值手机端不显示请选择配送方式
		$whereDeliveryDefault["isDefault"] = 1;
		$deliveryDefault =  $DeliveryTypeModel->where($whereDeliveryDefault)->find();
		$deliveryHasDefault = $deliveryDefault == NULL ? false : true;
		if ($selDeliveryType) {
			for ($i = 0; $i < count($deliveryType); $i++) {
				if ($selDeliveryType == $deliveryType[$i]["value"]) {
					$deliveryType[$i]["isDefault"] = 1;
					$deliveryHasDefault = true;
				} else {
					$deliveryType[$i]["isDefault"] = 0;
				}
			}
		}
		
		
		for ($i = 0; $i < count($deliveryType); $i++) {
			if ($deliveryType[$i]["value"] == ORDER_DELIVERYTYPE_DELIVERY) {
				$deliveryCost = $this->getDeliveryCost($prices, $points, $cids,$distributionId);
				if (!$deliveryCost) {
					return;
				}
				$deliveryType[$i]["value"] = $deliveryType[$i]["value"];
				$deliveryType[$i]["cost"] = $deliveryCost["cost"];
				$deliveryType[$i]["points"] = $deliveryCost["points"];
				break;
			}
		}
		$result["shipping"] = $deliveryType;
		$result["deliveryHasDefault"] = $deliveryHasDefault;
		
		
		// 将上次选择的支付方式设置为默认, 判断是否已经有默认值，没有默认值手机端不显示请选择支付方式
		$wherePayTypeDefault["isDefault"] = 1;
		$payTypeDefault =  $PayTypeModel->where($wherePayTypeDefault)->find();
		$payTypeHasDefault = $payTypeDefault == NULL ? false : true;
		if ($selPayType) {
			for ($i = 0; $i < count($payType); $i++) {
				if ($selPayType == $payType[$i]["value"]) {
					$payType[$i]["isDefault"] = 1;
					$payTypeHasDefault = true;
				} else {
					$payType[$i]["isDefault"] = 0;
				}
			}
		}
		$result["payType"] = $payType;
		$result["payTypeHasDefault"] = $payTypeHasDefault;
		return $result;
	}
	
	
	/*
	 * 根据支付金额获取运费
	 * cids : 拆单的客户id
	 */
	public function getDeliveryCost($prices, $points, $cids,$distributionId) {
		if (!empty($prices)) {
			$arr = explode(',', $prices);
		} else if (!empty($points)) {
			$arr = explode(',', $points);
		}
		$arrCid = explode(',', $cids);
		if (count($arr) == 0 || count($arrCid) == 0) {
		    $arr = [0];
//			Output::instance()->resultCode(code_system_error);
//			Log::write('[MallAction getDeliveryCost prices:]' .$prices . ',points:' . $points .',cids' . $cids);
//			return;
		}
		$countPrice = 0;
		$countPoints = 0;
		$costId = 0;
		$strCost = '';
		$strPoints = '';
		foreach ($arr as  $k => $value) {
			$CostModel = M('module_mall_delivery_cost', "wx_{$arrCid[$k]}_");
			$conditionCost["maxPrice"] = array('gt', $value);
			$conditionCost["distributionId"]=array("eq",$distributionId);
			$cost = $CostModel->where($conditionCost)->order("maxPrice asc")->find();
			Log::write('sql is ' .  $CostModel->getlastsql());
			if (!empty($cost["cost"])) {
				$countPrice += $cost["cost"];
				$strCost = $strCost . $cost["cost"] . ',';
			} else if (!empty($cost["points"])) {
				$countPoints +=  $cost["points"];
				$strPoints = $strPoints . $cost["points"] . ',';
			}
			if ($costId != 0 && $costId != $cost["id"]) {	
				// id如果不同则返回-1，后面逻辑判断如果是－1则不从当前客户表中获取物流信息
				$costId = -1;
			} else {
				$costId = $cost["id"];
			}
		}
		// 如果供应商id不是当前客户，且供应商不同，则costId设置为－1
		if ($costId != -1) {
			$customerId = Session::$user["customerId"];
			$lastCid = $arrCid[0];
			foreach ($arrCid as $cid) {
				if ($cid != $customerId) {
					$costId = -1;
					break;
				} else if ($lastCid != $cid) {
					$costId = -1;
					break;
				}
			}
		}
		if ($strCost != '') {
			$strCost = substr($strCost, 0, strlen($strCost) - 1); 
		}
		if ($strPoints != '') {
			$strPoints = substr($strPoints, 0, strlen($strPoints) - 1);
		}
		$result["cost"] = $countPrice;
		$result["points"] = $countPoints;
		$result["costId"] = $costId;
		$result["strCost"] = $strCost;
		$result["strPoints"] = $strPoints;
		return $result;
	}

	
	
	//---------------微商城模板改造2014-12-8------------------
	//加载模板属性列表
	public function getMallTplList($tplId){
		$malltplFunction = M("malltpl_function");
		$mallTpl = M("malltpl");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$mallTplArr = $mallTpl->alias("wmt")
		->field("wmt.functions")
		->where("wmt.id = $tplId")
		->find();
		$functions =  $mallTplArr["functions"];
		$malltplFunctionArr = $malltplFunction->alias("mf")
		->field("mf.id,mf.name,mf.imgUrl,mf.selectType")
		->where("mf.display=1 and mf.isAdd=1 and mf.id in($functions)")
		->select();
		if($malltplFunctionArr){
			Output::instance()->objArray($malltplFunctionArr);
		}else{
			Output::instance()->resultCode(code_success);
		}
	}
	
	
	public function isShowLogo(){
		$malltplFunction = M("malltpl_function");
		$mallTpl = M("malltpl");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		 
		$mallTplArr = $mallTpl->alias("wmt")
		->field("wmt.functions")
		->where("wmt.id = $tplId")
		->find();
		$functions =  $mallTplArr["functions"];
		$malltplFunctionCount= $malltplFunction->alias("mf")
		->where("mf.id in($functions) and mf.selectType ='logo'")
		->count();
		if($malltplFunctionCount>0){
			Output::instance()->resultCode(true);
		}else{
			Output::instance()->resultCode(false);
			 
		}
	
	}
	
	
	//加载货架模板
	public function getMallTemplates(){
		$mallTpl = M("malltpl");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$mallTplArr = $mallTpl->alias("mtpl")
		->where("mtpl.display=1")
		->select();
		if($mallTplArr){
			Output::instance()->objArray($mallTplArr);
		}else{
			Output::instance()->resultCode(code_success);
		}
	
	}
	
	
    /**
     * 获取发票内容
     */
    public function getInvoiceContent($interface = false){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $invoiceContentModule = m('user_invoice_content');
        $result = $invoiceContentModule->select();

        if($interface){
            return $result;
        }else{
            if ($result) {
                Output::instance()->objArray($result);
            } else {
                Output::instance()->resultCode();
            }
        }
    }

    public function getInvoiceMethod($interface = false){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $invoiceContentModule = m('user_invoice_method');
        $result = $invoiceContentModule->select();

        if($interface){
            return $result;
        }else{
            if ($result) {
                Output::instance()->objArray($result);
            } else {
                Output::instance()->resultCode();
            }
        }
    }

    public function updateInvoiceContent($invoiceContent, $id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $invoiceContentModule = m('user_invoice_content');
        $data['name'] = $invoiceContent;
        $where['id'] = $id;
        $result = $invoiceContentModule->where($where)->save($data);

        if ($result !== false) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    public function addInvoiceContent($invoiceContent){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $invoiceContentModule = m('user_invoice_content');
        $data['name'] = $invoiceContent;
        $result = $invoiceContentModule->add($data);

        if ($result !== false) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

     public function delInvoiceContent($id){
         $retVal = Session::init();
         if (!$retVal) {
             Output::instance()->resultCode(code_access_denied);
             return;
         }

         $invoiceContentModule = m('user_invoice_content');
         $where['id'] = $id;
         $result = $invoiceContentModule->where($where)->delete();

         if ($result !== false) {
             Output::instance()->resultCode();
         } else {
             Output::instance()->resultCode(code_sql_error);
         }
     }

    public function getInvoiceSetting($interface = false){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        $superSetting = m("customer_super_setting", 'wx_');
        $invoice = $superSetting->where("customerId = {$cid}")->find();
        if($interface){
            return $invoice;
        }else{
            if ($invoice) {
                Output::instance()->object($invoice);
            } else {
                Output::instance()->resultCode();
            }
        }

    }

    public function setInvoiceSetting($isInvoice){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }


        $cid = Session::$user['customerId'];
        $superSetting = m("customer_super_setting", 'wx_');
        $where['customerId'] = $cid;
        $data['isInvoice'] = $isInvoice;
        $result = $superSetting->where($where)->save($data);

        if ($result !== false) {
            Output::instance()->resultCode();
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }
    
    public function getInvoice($fromUserName, $invoiceId = 0){
    	$retVal = Session::init();
    	if (!$retVal) {
    		Output::instance()->resultCode(code_access_denied);
    		return;
    	}
    
    	$cid = Session::$user['customerId'];
    	$invoiceModel = m('user_invoice');
    	$where['inv.fromUserName'] = $fromUserName;
    	$where['inv.deleted'] = array('eq', 0);
    	if(intval($invoiceId) != 0) {
    		$where['inv.id'] = array('eq', $invoiceId);
    	}
    	$result = $invoiceModel
	    	->alias("inv")
	    	->join("wx_{$cid}_user_invoice_content invContent on inv.contentTypeId = invContent.id")
	    	->join("wx_{$cid}_user_invoice_method invMethod on inv.methodId = invMethod.id")
	    	->field("inv.*, invContent.name as contentName, invMethod.name as methodName")
	    	->where($where)
	    	->select();
    	return $result;
    }
    

    public function addInvoice($cid, $userName,$title, $titleName, $contentTypeId, $methodId, $interface = false){
        $check = $this->checkInvoice($cid, $userName,$title, $titleName, $contentTypeId, $methodId, $interface);
        if($check){
            $invoiceModel = m('user_invoice', "wx_{$cid}_");
            $data['fromUserName'] = $userName;
            $data['title'] = $title;
            $data['titleName'] = ($title == '2') ? $this->getFullName($cid, $userName) : $titleName;
            $data['contentTypeId'] = $contentTypeId;
            $data['methodId'] = $methodId;
            $data['createTime'] = date('Y-m-d H:i:s');
            $result = $invoiceModel->add($data);
            if($interface){
                return $result;
            }else{
                if ($result !== false) {
                    Output::instance()->resultCode();
                } else {
                    Output::instance()->resultCode(code_sql_error);
                }
            }
        }else{
            return $check;
        }
    }

    public function getFullName($cid, $fromUserName){
        $userInfo = m('user_info',"wx_{$cid}_");
        $where['fromUserName'] = $fromUserName;

        return $userInfo->where($where)->getField('fullName');
    }

    public function updateInvoice($cid, $invoiceId, $userName, $title, $titleName, $contentTypeId, $methodId, $interface = false){
        $check = $this->checkInvoice($cid, $invoiceId, $userName,$title, $titleName, $contentTypeId, $methodId, $interface);
        if($check){
            $invoiceModel = m('user_invoice',"wx_{$cid}_");
            $data['fromUserName'] = $userName;
            $data['title'] = $title;
            $data['titleName'] = ($title == '2') ? $this->getFullName($cid, $userName) : $titleName;
            $data['contentTypeId'] = $contentTypeId;
            $data['methodId'] = $methodId;
            $data['updateTime'] = date('Y-m-d H:i:s');

            $where['id'] = $invoiceId;
            $result = $invoiceModel->where($where)->save($data);
            if($interface){
                return $result;
            }else{
                if ($result !== false) {
                    Output::instance()->resultCode();
                } else {
                    Output::instance()->resultCode(code_sql_error);
                }
            }
        }else{
            return $check;
        }
    }

    /**
     * [setmallStoremsg 微商城店铺设置]
     * @param  [type] $name       [店铺名称]
     * @param  [type] $storeurl   [店铺地址]
     * @param  [type] $wechatname [公众号名称]
     * @param  [type] $wechaturl  [公众号地址]
     * @param  [type] $logo       [店铺logo]
     * @return [type]             [description]
     */
    public function setmallStoremsg($name,$storeurl,$wechatname,$wechaturl,$logo,$recommend,$qrcodeBack=null,$qrcodeLocation=null,$qrcodeSize=null,$mallHue=0,$isUserNameLogin=null,$isPhoneLogin=null,$isVerifyPhone=null){
    	$retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$quanuserVendor = M("module_quanuser_vendor");
		Session::switchCustomer($cid);
       	$MallStoreModel = m('module_mall_store');
       	$data['name'] = $name;
       	$data['storeurl'] = $storeurl;
       	$data['wechatname'] = $wechatname;
       	$data['wechaturl'] = $wechaturl;
       	$data['logo'] = $logo;
		$data["recommend"] = $recommend;
       	$arr = $MallStoreModel->find();
		$data['qrcodeBack']=$qrcodeBack;
		$data['qrcodeLocation']=$qrcodeLocation;
		$data['qrcodeSize']=$qrcodeSize;
		$data['mallHue']=$mallHue;
		$data['isUserName']=$isUserNameLogin;
		$data['isPhoneLogin']=$isPhoneLogin;
		$data['isVerifyPhone']=$isVerifyPhone;
        if ($arr['qrcodeBack'] != $qrcodeBack || $data['qrcodeLocation'] == $qrcodeLocation || $data['qrcodeSize'] != $qrcodeSize) {
			$quanuserVendor->where("cId=$cid")->setField("qrcode","");
		}
       	if ($arr) {
			$where['id'] = $arr['id'];
       		$result = $MallStoreModel->where($where)->save($data);
			self::cacheDel($cid);
       	}else{
       		$result = $MallStoreModel->add($data);
       	}
       	if ($result !== false) {
			 Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

    }
    
   		/**
   		 * [getmallStoremsg 拿取店铺设置]
   		 * @return [type] [description]
   		 */
    public function getmallStoremsg(){
    	$retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		Session::switchCustomer($cid);
    	$MallStoreModel = m('module_mall_store');
		$where['fromCustomerId']=array("eq",$cid);
		$where['deleted']=array("eq",0);
    	$arr = $MallStoreModel->alias("a")
			->field("a.*")->find();
		if($arr){
			$batchSetting = json_decode($arr['json'],true);
			if($batchSetting){
				$arr = array_merge($arr,$batchSetting);
			}
		}
		if($arr['qrcodeLocation']){
			$location = explode("|",$arr['qrcodeLocation']);
			$arr['codeLocationX']=$location[0];
			$arr['codeLocationY']=$location[1];
		}
		if($arr['qrcodeSize']){
			$size = explode("*",$arr['qrcodeSize']);
			$arr['codeSizeX']=$size[0];
			$arr['codeSizeY']=$size[1];
		}
		Output::instance()->object($arr);

    }
	//保存批量发货设置
	public function saveBatchSetting($json){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer($cid);
		$MallStoreModel = M('module_mall_store');
		$result = $MallStoreModel->where("1=1")->setField("json",$json);
		if($result!==false){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}

	//货架分享设置
	public function getMallShareStore($mallId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$shareStore = M("module_mall_share_store");
		Session::switchCustomer($cid);
		$arr = $shareStore->where("mallId=".$mallId." and customerId = ".$cid)->find();
		Output::instance()->object($arr);

	}

	//保存货架分享设置
	public function saveMallShareStore($mallId,$mallShareTitle,$mallShareDesc,$mallShareUrl,$mallShareLogo){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$shareStore = M("module_mall_share_store");
		Session::switchCustomer($cid);
		$data["mallId"] = $mallId;
		$data["mallShareTitle"] = $mallShareTitle;
		$data["mallShareDesc"] = $mallShareDesc;
		$data["mallShareLogo"] = $mallShareLogo;
		$data["mallShareUrl"] = $mallShareUrl;
		$data["customerId"] = $cid;
		$info = $shareStore->where("mallId=".$mallId." and customerId = ".$cid)->find();
		if($info){
			$shareStore->where("id=".$info["id"])->save($data);
		}else{
			$shareStore->add($data);
		}
		Output::instance()->resultCode();
	}

    /**
     * [gettemplatemsgList 模板消息列表]
     * @return [type] [description]
     */
    public function gettemplatemsgList($start=0,$limit=10){
    	$retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $MallTepmsgModel = m('template_messages');
        $result = $MallTepmsgModel->limit($start,$limit)->select();
        if($result){
				$count = $MallTepmsgModel->count();
				Output::instance()->objArray($result,$count);
			}else{
				Output::instance()->resultCode(code_success);
			}

    }

    /**
     * [gettemplatemsgById 拿到制定模板消息]
     * @param  [type] $id [id]
     * @return [type]     [description]
     */
    public function gettemplatemsgById($id){
    	$retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
		Session::switchCustomer($cid);
        $MallTepmsgModel = m('template_messages');
        $where['id'] = $id;
        $arr = $MallTepmsgModel->where($where)->find();
        if ($arr) {
			Output::instance()->object($arr);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
    }

    /**
     * [savetemplatemsg 保存模板消息]
     * @param  [type] $id         [id
     * @param  [type] $templateId [模板消息id]
     * @param  [type] $status     [状态]
     * @return [type]             [description]
     */
    public function savetemplatemsg($id,$name,$templateId,$status,$content){
    	$retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
		Session::switchCustomer($cid);
        $MallTepmsgModel = m('template_messages');
        $where['id'] = $id;
        $data['templateId'] = $templateId;
        $data['templateContent'] = $content;
        $data['status'] = $status;
        $data['name']=$name;
        $result = $MallTepmsgModel->where($where)->save($data);
        if ($result !== false) {
				$data["id"] = $id;
				Output::instance()->object($data);
			}else {
				  Output::instance()->resultCode(code_sql_error);
		}
    }

    /**
     * [addtemplatemsg 增加模板消息]
     * @param  [type] $templateId [模板消息id]
     * @param  [type] $status     [状态]
     * @return [type]             [description]
     */
    public function addtemplatemsg($name,$templateId,$status,$content){
    	$retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $MallTepmsgModel = m('template_messages');
        $data['templateId'] = $templateId;
        $data['status'] = $status;
        $data['templateContent'] = $content;
        $data['name']=$name;
        $result = $MallTepmsgModel->add($data);
        if ($result !== false) {
			Output::instance()->resultCode();
		}else {
			Output::instance()->resultCode(code_sql_error);
		}
    }

   	/**
   	 * [deltemplatemsg 删除模板消息]
   	 * @param  [type] $id [id]
   	 * @return [type]     [description]
   	 */
    public function deltemplatemsg($id){
    	$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			$cid = Session::$user['customerId'];
        	$MallTepmsgModel = m('template_messages');
			$where['id'] = $id;
			$result = $MallTepmsgModel->where($where)->delete();
			if ($result) {
				Output::instance()->resultCode(code_success);			
			} else {
				Output::instance()->resultCode(code_sql_error);
			}
    }
	public function distributionList($name='',$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer($cid);
		$distriScheme = M("module_distribution_scheme");
		$where['deleted'] = array('eq',0);
		$where['name'] = array('like',"%$name%");
		$arr = $distriScheme->where($where)->limit($start,$limit)->select();
		if($arr){
			$count = $distriScheme->where($where)->count();
			Output::instance()->objArray($arr,$count);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * 删除商店配置缓存数据
	 * @param $cId /cid
	 */
	protected function cacheDel($cId){
		$redis = new RedisAPI();
		$redis->del('cid'.$cId.'mallInfo');
	}

	/**
	 * 设置爱农支付配置信息
	 * @param $merId		商户id
	 * @param $key			商户秘钥
	 */
	public function setAiNongPaySetting($merId, $key){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$CustomerMallSettingModel = D('customer_mall_ainongpay_setting');
		Session::switchCustomer($customerId);
		$time = date('Y-m-d H:i:s');
		$data['merId'] = $merId;
		$data['key'] = $key;
		$data['updateTime'] = $time;

		$condition['customerId'] = array('eq',$customerId);
		$mallSetting = $CustomerMallSettingModel->where($condition)->find();

		if($mallSetting){
			$result = $CustomerMallSettingModel->where($condition)->save($data);
		}else{
			$data['customerId'] = $customerId;
			$data['createTime'] = $time;
			$result = $CustomerMallSettingModel->add($data);
		}

		if ($result !== false) {
			Output::instance()->resultCode();
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * 获取爱农支付配置信息
	 */
	public function getAiNongPaySetting(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerMallSettingModel = D('customer_mall_ainongpay_setting');

		$condition['customerId'] = $customerId;
		$result = $CustomerMallSettingModel->where($condition)->find();
		if ($result) {
			Output::instance()->object($result);
		} else {
			Output::instance()->resultCode();
		}
	}

	/** 商城管理菜单 */
	public function getMallMenu(){
        $mediaId=1;
        // 菜单配置数组
        $data = [
            'mall'    => [
                'group'     => '商城设置',
                'children'  => [
                    [
                        'name'  => '主商城设置',
                        'url'   => '#/joymap/eshopManage/baseConfig',
                    ],
                    [
                        'name'  => '商城风格',
                        'url'   => '#/joymap/eshopManage/style',
                    ],
                    [
                        'name'  => '推广二维码设置',
                        'url'   => '#/joymap/eshopManage/qrcode',
                    ],
                    [
                        'name'  => '配送方式管理',
                        'url'   => '#/joymap/eshopManage/distribution',
                    ],
                    [
                        'name'  => '支付方式设置',
                        'url'   => '#/joymap/eshopManage/pay',
                    ],
//                    [
//                        'name'  => '发票管理',
//                        'url'   => '#/joymap/selfmedia/detail/' . $mediaId . '/newsComment',
//                    ],
//                    [
//                        'name'  => '货架管理',
//                        'url'   => '#/joymap/eshopManage/rack',
//                    ]
                ]
            ]
        ];

        $index = 1;
        $arr_child = [];
        foreach ($data['mall']['children'] as $child_k => $child_v) {
            // 这个菜单是_胡英俊_给出的菜单树demo结构
            $m = [
                'id'        => $index,
                'name'      => $child_v['name'],
                'level'     => 1,
                'parent'    => 0,
                'path'      => "$index",
                'icon'      => '',
                'url'       => $child_v['url'],
                'isMenu'    => true,
                'children'  => []
            ];
            array_push($arr_child, $m);
            $index++;
        }

        $menu = [
            'id'        => 0,
            'group'     => $data['mall']['group'],
            'children'  => $arr_child
        ];


        Output::instance()->object(['data' => [$menu]]);
    }
}